package su.samlib.informer;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import su.samlib.informer.model.Author;
import su.samlib.informer.model.Book;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;

public class AuthorTextsActivity extends Activity {
	
	private ListView authorTextsView;
	private Author author;
	
	@Override
	public void onCreate(Bundle saveInstanceState) {
		super.onCreate(saveInstanceState);
		setContentView(R.layout.author_text_activity);
		authorTextsView = (ListView) findViewById(R.id.TextsList);
		authorTextsView.setSmoothScrollbarEnabled(false);
		
		author = getIntent().getParcelableExtra("author");
		List<Book> texts = getIntent().getParcelableArrayListExtra("authorTexts");
		
		authorTextsView.setOnItemClickListener(new OnItemClickListener() {
			@SuppressWarnings("unchecked")
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				
				@SuppressWarnings("unused")
				String itemname = new Integer(arg2).toString();
				// TODO Auto-generated method stub
				Map<String, Object> map = (HashMap<String, Object>) arg0
						.getItemAtPosition(arg2);
				
				final String bookUrl = author.getLibraryId().getLibraryUrl()
						+ author.getAuthorUri() 
						+ (String) map.get("link");
				
				Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(bookUrl));
				startActivity(i);
			}
		});


		
		List<Map<String, ?>> items = new LinkedList<Map<String, ?>>();
		for (Book text : texts) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("title", text.getTitle());
			map.put("description", text.getBookDescription());
			map.put("isNew", text.isNew() ? R.drawable.star_yellow_new16
					: R.drawable.star_grey16);
			map.put("link", text.getBookUri());
			items.add(map);
		}

		SimpleAdapter adapter = new SimpleAdapter(this, items,
				R.layout.author_text_item, new String[] { "title", "description",
						"isNew" }, new int[] { R.id.title, R.id.description,
						R.id.isNew });
		authorTextsView.setAdapter(adapter);
		
	}
	

}
